package com.base.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LogInterceptor extends AbstractInterceptor {

	private static final Log logger = LogFactory.getLog(LogInterceptor.class);
	private static final String FINISH_MESSAGE = "action后置通知";
	private static final String START_MESSAGE = "action前置通知";
	private static final String START_MESSAGE1 = "方法开始执行!";
	private static final String FINISH_MESSAGE1 = "方法执行结束！";
	public String intercept(ActionInvocation invocation) throws Exception {

		long startTime = System.currentTimeMillis();
		logMessage(invocation, START_MESSAGE,START_MESSAGE1);
		String result = invocation.invoke();
		
		long executionTime = System.currentTimeMillis() - startTime;
		String timeString="action耗时"+(executionTime)+"毫秒！";
		logMessage(invocation, FINISH_MESSAGE,FINISH_MESSAGE1+timeString);
		return result;
	}

	private void logMessage(ActionInvocation invocation, String baseMessage, String baseMessage1) {
		if (logger.isInfoEnabled()) {
			StringBuilder message = new StringBuilder(baseMessage);
			String namespace = invocation.getProxy().getNamespace();

			if ((namespace != null) && (namespace.trim().length() > 0)) {
				message.append(invocation.getAction().getClass().getName()).append("类的")
					.append(invocation.getProxy().getMethod()).append(baseMessage1);
			}
			logger.info(message.toString());
		}
	}

}
